﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Core.DataAccess.IRepositories;

namespace Core.DataAccess.Repositories
{
    [Export(typeof(IPermissionRepository))]
    public class PermissionRepository : IPermissionRepository
    {
        private Connection conn;
        public PermissionRepository()
        {
            conn = new Connection();
        }

        public List<Permission> GetPermissionsByAccountID(Int32 AccountID)
        {
            using (MXHEntities context = conn.GetContext())
            {

                var permissions = from p in context.Permissions
                                  join ap in context.AccountPermissions on p.PermissionID equals ap.PermissionID
                                  join a in context.Accounts on ap.AccountID equals a.AccountID
                                  where a.AccountID == AccountID
                                  select p;

                return permissions.ToList();
            }
        }

        public List<Permission> GetPermissionByName(string Name)
        {

            using (MXHEntities context = conn.GetContext())
            {
                var permissions = from p in context.Permissions.Where(p => p.Name.Equals(Name))
                                  select p;

                return permissions.ToList();

            }
        }

        public List<Permission> GetPermissionByID(Int32 PermissionID)
        {
            List<Permission> returnPermissions = new List<Permission>();

            using (MXHEntities context = conn.GetContext())
            {
                var permissions = from p in context.Permissions.Where(p => p.PermissionID.Equals(PermissionID))
                                  select p;

                return returnPermissions.ToList();
            }
        }

        public void SavePermission(Permission permission)
        {
            using (MXHEntities context = conn.GetContext())
            {
                if (permission.PermissionID <= 0)
                {
                    context.Permissions.AddObject(permission);
                }
                else
                {
                    context.Permissions.ApplyCurrentValues(permission);
                }
                context.SaveChanges();
            }
        }

        public void DeletePermission(Permission permission)
        {
            using (MXHEntities context = conn.GetContext())
            {
                context.DeleteObject(permission);
                context.SaveChanges();
            }
        }
    }
}
